import 'package:dio/dio.dart';
import 'package:flutter_wisave/LoginPage/LoginPage.dart';
import '../Tools/ToolsLocalStorage.dart'; // 导入本地存储工具
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class NetworkService {
  static final NetworkService _instance = NetworkService._internal();
  factory NetworkService() => _instance;

  Function? onUnauthorized;

  NetworkService._internal();

  final Dio _dio = Dio(BaseOptions(
    baseUrl: 'http://47.97.244.170:8080', //'http://8.137.93.51:8080',
    connectTimeout: const Duration(milliseconds: 5000),
    receiveTimeout: const Duration(milliseconds: 3000),
  ));

  Dio get dio => _dio;

  // Setup Dio interceptor
  void setupInterceptors(BuildContext? context) {
    bool isLoginPageShown = false; // 添加标志位

    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        final token = await LocalStorage.getstr('token');
        if (token != null && token.isNotEmpty) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        print('Request: ${options.method} ${options.uri}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print('Response: ${response.statusCode} ${response.data}');
        if (response.data is Map) {
          if (response.data['code'] == 200) {
            return handler.next(response);
          } else if (response.data['code'] == 401) {
            // Call the onUnauthorized callback if set
            // 弹出登录页面
            if (context != null &&
                !isLoginPageShown &&
                context.widget.toString() != 'LoginPage') {
              isLoginPageShown = true; // 设置标志位
              // Navigator.of(context, rootNavigator: true).push(
              //   MaterialPageRoute(builder: (context) => const LoginPage()),
              // ).then((_) {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const LoginPage()),
              ).then((_) async {
                // 登录页面关闭后，继续处理原来的请求
                isLoginPageShown = false; // 重置标志位
                // 触发原页面的 initState 函数
                if (context != null && context.mounted) {
                  (context as StatefulElement).state.initState();
                }
                handler.next(response);
              });
            }
          } else {
            if (context != null) {
              TDToast.showText(response.toString(), context: context);
            }
            // 处理其他非 200 状态码
            return handler.reject(
              DioException(
                requestOptions: response.requestOptions,
                response: response,
                type: DioExceptionType.badResponse,
                error: 'API returned non-200 code: ${response.toString()}',
              ),
            );
          }
        }
        // else {
        //   isLoginPageShown = true; // 设置标志位
        //   Navigator.push(
        //     context!,
        //     MaterialPageRoute(builder: (context) => const LoginPage()),
        //   ).then((_) async {
        //     // 登录页面关闭后，继续处理原来的请求
        //     isLoginPageShown = false; // 重置标志位
        //     // 触发原页面的 initState 函数
        //     if (context != null && context.mounted) {
        //       (context as StatefulElement).state.initState();
        //     }
        //     handler.next(response);
        //   });
        // }
        // 如果响应数据不是 Map 类型，则继续处理
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        // Handle errors
        print('Error: ${e.message}');
        // isLoginPageShown = true; // 设置标志位
        // Navigator.push(
        //   context!,
        //   MaterialPageRoute(builder: (context) => const LoginPage()),
        // ).then((_) async {
        //   // 登录页面关闭后，继续处理原来的请求
        //   isLoginPageShown = false; // 重置标志位
        //   // 触发原页面的 initState 函数
        //   if (context != null && context.mounted) {
        //     (context as StatefulElement).state.initState();
        //   }
        //   handler.next(e);
        // });
        return handler.next(e); // Continue
      },
    ));
  }

  // Example GET request
  Future<Response> get(String path,
      {Map<String, dynamic>? queryParameters}) async {
    try {
      final response = await _dio.get(path, queryParameters: queryParameters);

      return response; // 直接返回响应，错误处理已在拦截器中完成
      // if (response.data['code'] == 200) {
      //   return response;
      // } else if (response.data['code'] == 401) {
      //   // Call the onUnauthorized callback if set
      //   // 弹出登录页面
      //   if (context != null && context.widget.toString() != 'LoginPage') {
      //     Navigator.push(
      //       context,
      //       MaterialPageRoute(builder: (context) => const LoginPage()),
      //     ).then((_) {
      //       // 登录页面关闭后，继续处理原来的请求
      //       // handler.next(response);
      //     });
      //   }
      // }
      // // 处理其他非 200 状态码
      // throw DioException(
      //   requestOptions: RequestOptions(path: path),
      //   type: DioExceptionType.badResponse,
      //   error: 'API returned non-200 code: ${response.data['code']}',
      // );
    } on DioException catch (e) {
      print('DioException in get method: ${e.message}');
      rethrow;
    }
  }

  // Example POST request
  Future<Response> post(String path, {Map<String, dynamic>? data}) async {
    try {
      final response = await _dio.post(path, data: data);
      return response; // 直接返回响应，错误处理已在拦截器中完成
    } on DioException catch (e) {
      print('DioException in post method: ${e.message}');
      rethrow;
    }
  }
}
